import os
import sys
import numpy as np
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class ArtistWidget(QTableWidget):
    def __init__(self,project_data,artist_data):
        super(ArtistWidget, self).__init__()
        """
        :param project_data: [(项目1,预算),(项目2,预算),(项目3,预算),...]
        :param artist_data: [(人名1,个人总工时,是否研发),(人名2,个人总工时,是否研发),...]
        """
        self.project_data=project_data
        self.artist_data=artist_data
        self.salary_map={}   #从人事那边读取的人员工资表{'人名1':xxx,'人名2':xxxx}
        self.h_head_map_list=[]
        self.h_headlist=self.getH_HeadList(self.project_data)
        self.artist_list, self.artist_map = self.init_artist(self.artist_data)
        self.init_items()
        self.setHorizontalHeaderLabels(self.h_headlist)
        self.setVerticalHeaderLabels(self.artist_list)

        self.cellChanged.connect(self.change)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.rightMenu)
        # self.ai_count()

    def set_data(self,project_data,artist_data):
        print('project_data:',project_data)
        print('artist_data:',artist_data)
        self.project_data = project_data
        self.artist_data = artist_data
        # self.salary_map = {}  # 从人事那边读取的人员工资表{'人名1':xxx,'人名2':xxxx}
        # self.h_head_map_list = []
        print('set_data001')
        self.h_headlist = self.getH_HeadList(self.project_data)
        print('set_data002')
        self.artist_list, self.artist_map = self.init_artist(self.artist_data)
        print('set_data003')
        self.init_items()
        print('set_data004')
        self.setHorizontalHeaderLabels(self.h_headlist)
        print('set_data005')
        self.setVerticalHeaderLabels(self.artist_list)
        print('set_data006')

    def update_H(self,project_data):
        """
        更新表头项目
        :param project_data:
        :return:
        """
        self.project_data=project_data
        self.h_headlist=self.getH_HeadList(project_data)
        self.setHorizontalHeaderLabels(self.h_headlist)

    def rightMenu(self):
        r_menu=QMenu()
        test_action=QAction('测试',self)
        test_action.triggered.connect(self.test)
        r_menu.addAction(test_action)
        r_menu.exec_(QCursor.pos())


    def init_items(self):
        h_count=len(self.h_headlist)
        v_count=len(self.artist_list)
        self.setColumnCount(h_count)
        self.setRowCount(v_count)
        for r in range(v_count):
            for c in range(h_count):
                item=QTableWidgetItem()
                item.setBackground(QBrush(QColor('#F0FFFF')))
                item.setText('1')
                item.setTextAlignment(Qt.AlignCenter)
                if c in [0,1]:
                    item.setFlags(Qt.NoItemFlags)
                self.setItem(r,c,item)

        for artist in self.artist_list:
            row=self.artist_list.index(artist)
            workhour=self.artist_map[artist][1]
            RD=self.artist_map[artist][2]
            workhour_item=self.item(row,1)
            workhour_item.setText(str(workhour))
            RD_item=self.item(row,2)
            RD_item.setText(str(RD))

            if RD!=1:
                self.freezeRow(row)

    def getH_HeadList(self,project_data):
        """
        生成水平表头列表
        :param project_data:
        :return:
        """
        origin_list=['工资','个人总工时','是否研发']
        origin_map_list=[0,1,2]
        project_list=[]
        project_map_list=[]
        if project_data:
            for i in project_data:
                project_show_name=f'{i[0]}'+'\n'+f'{i[1]}'+'|0'
                project_list.append(project_show_name)
                project_map_list.append(i[0])
        origin_list.extend(project_list)
        origin_map_list.extend(project_map_list)
        self.h_head_map_list=origin_map_list

        return origin_list

    def init_artist(self,artist_data):
        artist_list=[]
        artist_map={}
        if artist_data:
            for i in artist_data:
                artist_list.append(i[0])
                artist_map[i[0]]=i
        return artist_list,artist_map

    def freezeRow(self,r):
        """
        冻结清空该行
        :return:
        """
        c_count=self.columnCount()
        for c in range(3,c_count):
            item=self.item(r,c)
            item.setText('0')
            item.setFlags(Qt.NoItemFlags)

    def unFreezeRow(self,r):
        """
        冻结清空该行
        :return:
        """
        c_count=self.columnCount()
        for c in range(3,c_count):
            item=self.item(r,c)
            # item.setText('0')
            new_item=QTableWidgetItem()
            new_item.setBackground(QBrush(QColor('#F0FFFF')))
            new_item.setText('0')
            new_item.setTextAlignment(Qt.AlignCenter)
            # item.setFlags(Qt.ItemIsEditable)
            self.setItem(r,c,new_item)

    def setSalary(self,salary_data):
        self.salary_map=salary_data
        # print("salary_map:",self.salary_map)
        for i in self.artist_list:
            if i in salary_data.keys():
                # salary=salary_data[i]
                salary_item=self.item(self.artist_list.index(i),0)
                salary_item.setText('****')
                # salary_item.setText(str(self.salary_map[i]))

    def checkRD(self,r,c):
        """
        直接通过检测是否为研发人员来更改行信息
        :return:
        """

        RD_item=self.item(r,2)
        RD=RD_item.text()
        if RD !='1':
            self.freezeRow(r)
        else:
            # print('恢复研发')
            self.unFreezeRow(r)


    def change(self,r,c):
        # print(r,c)
        if c==2:  #如果改变来自第二行RD
            self.checkRD(r,c)
        elif c not in [0,1,2]:
            # print('一开始就ai_count了？')
            try:
                self.ai_count()
            except Exception as change_ERR:
                print(str(change_ERR))


    def ai_row(self,r):
        """
        计算当前行中的比例系数对应的工资与工时 ,注意要过滤掉非研发人员
        :param r:
        :return:
        """
        # print('ai_row start')
        artist=self.artist_list[r]
        # info=self.artist_data[artist]
        salary=float(self.salary_map[artist])  #拿到个人工资
        # print('salary: ',salary)
        workhour=float(self.artist_map[artist][1])
        # print('ai_row 01')
        project_salary_list=[]  #每项目工资分配
        per_workhour_list=[]   #每项目工时分配
        project_percent_list=[]
        total_percent=0    #所有系数总和

        for c in range(3,self.columnCount()): #获取该行比例系数
            item=self.item(r,c)
            text=item.text() if item.text() else '0'
            project_percent_list.append(float(text))
            total_percent+=float(text)
            # print('ai_row 02')
        if total_percent:  #保证不为0
            for i in project_percent_list:
                per_salary=(salary/10000)*i/total_percent  #以万为单位
                project_salary_list.append(per_salary)
                per_workhour=workhour*i/total_percent
                per_workhour_list.append(per_workhour)
            # print('ai_row 03')
        return project_salary_list,per_workhour_list

    def ai_count(self):
        """
        检测数据
        :return:
        """
        all_row_salary_list=[]
        all_row_workhour_list=[]

        for r in range(self.rowCount()):
            RD_item=self.item(r,2)
            # print('ai_count01')
            RD=RD_item.text()
            if RD == '1':
                # print('ai_count02')
                per_salary_list,per_workhour_list=self.ai_row(r)
                # print('ai_count03')
                all_row_salary_list.append(per_salary_list)
                all_row_workhour_list.append(per_workhour_list)
        if all_row_salary_list:
            # print('all_row_salary_list:',all_row_salary_list)
            all_row_salary_array=np.array(all_row_salary_list)
            project_counts=len(self.project_data)
            print('ai_count04')
            print(all_row_salary_array)
            for i in range(project_counts):
                # print('ai_count05')
                print(i)
                per_project_all_salary=round(all_row_salary_array[:,i].sum(),2)
                # print('ai_count06')
                project_show_name=f'{self.project_data[i][0]}'+'\n'+f'{self.project_data[i][1]}'+f'|{per_project_all_salary}'
                self.horizontalHeaderItem(i+3).setText(project_show_name)  #注意项目的表头索引
                # print('ai_count07')


    def test(self):
        print(self.ai_row(0))


class ResignedWindow(QWidget):

    def __init__(self,project_list,artist_data):
        super(ResignedWindow, self).__init__()
        #全局变量
        self.project_list=project_list
        self.artist_data=artist_data #[(人名1,个人总工时,是否研发),(人名2,个人总工时,是否研发),...]  eg:[(人名,'15000',1)]
        self.project_edit_list=[] #分项目总额edit列表
        self.month_edit_list=[] #分项目月份edit列表
        self.per_month_value_label_list=[]#每月平均额edit列表
        self.all_cost=0  #所有项目总预算


        self.m_font=QFont('',12)
        self.l_font = QFont('', 10)
        self.setWindowTitle('工资重分配')
        self.main_layout=QHBoxLayout()
        self.setMinimumWidth(1500)
        self.hSplitter = QSplitter(Qt.Horizontal)
        self.left_frame=QFrame()
        self.left_layout = QVBoxLayout()
        self.left_layout.setAlignment(Qt.AlignTop|Qt.AlignHCenter)
        self.left_layout.setSpacing(15)
        ar_font=QFont('',15)
        self.left_label = QLabel('参数设置')
        self.left_label.setFont(ar_font)
        self.left_label.setAlignment(Qt.AlignTop|Qt.AlignHCenter)
        self.spline=QLabel()
        self.spline.setFixedHeight(2)
        self.spline.setMinimumWidth(50)
        self.spline.setAlignment(Qt.AlignHCenter)
        self.spline.setStyleSheet('background-color:#696969')
        self.patch_btn = QPushButton('获取人员工资')
        self.patch_btn.clicked.connect(self._set_salary)
        btn_style=''' QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                  QPushButton{background-color:#FFDEAD}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px} '''
        self.patch_btn.setStyleSheet(btn_style)
        self.all_project_setting_layout = QVBoxLayout()
        self.all_project_setting_layout.setAlignment(Qt.AlignHCenter)
        self.all_project_setting_layout.setSpacing(10)
        self.all_project_setting_layout.setContentsMargins(5,15,5,0)
        rex=QRegExp("[0-9\.]+$")
        self.rv=QRegExpValidator(rex,self)
        label_font=QFont('',10,75)
        self.all_project_cost_label = QLabel('所有项目总预算(万元)')
        self.all_project_cost_label.setAlignment(Qt.AlignHCenter)
        self.all_project_cost_label.setFont(label_font)
        self.all_project_cost_layout=QHBoxLayout()
        self.all_project_cost_layout.setAlignment(Qt.AlignHCenter)
        self.all_project_cost_layout.setContentsMargins(100,10,20,10)
        self.all_project_cost_edit = QLineEdit()
        self.all_project_cost_edit.setMaximumWidth(110)
        self.all_project_cost_edit.setAlignment(Qt.AlignCenter)
        self.all_project_cost_edit.setValidator(self.rv)
        self.all_project_cost_edit.textChanged.connect(self._all_cost_changed)
        self.ye='    余额： {}'.format(0)
        self.all_project_left_cost_label=QLabel(self.ye)
        self.all_project_cost_layout.addWidget(self.all_project_cost_edit)
        self.all_project_cost_layout.addWidget(self.all_project_left_cost_label)
        self.all_project_setting_layout.addWidget(self.all_project_cost_label)
        # self.all_project_setting_layout.addWidget(self.all_project_cost_edit)
        self.all_project_setting_layout.addLayout(self.all_project_cost_layout)
        # self.all_project_setting_layout.addWidget(self.spline1)
        self.spline1=QLabel()
        self.spline1.setStyleSheet('background-color:#696969')
        self.spline1.setFixedHeight(2)
        self.spline1.setMinimumWidth(50)
        self.spline1.setAlignment(Qt.AlignHCenter)

        self.project_widget = QWidget()
        self.project_widget.setMaximumWidth(450)
        self.project_scroll = QScrollArea()
        self.project_UI = QVBoxLayout()
        self.project_UI.setAlignment(Qt.AlignHCenter)
        self.project_widget.setLayout(self.project_UI)

        self.project_UI.setContentsMargins(5,15,5,5)
        self.project_setting_layout=QHBoxLayout()
        self.project_setting_layout.setSpacing(15)
        self.import_btn=QPushButton('导入预设')
        self.import_btn.setStyleSheet(btn_style)
        self.import_btn.clicked.connect(self.import_prefab)
        self.per_project_label=QLabel('各项目预算(万元)')
        self.per_project_label.setFont(label_font)
        self.per_project_label.setAlignment(Qt.AlignTop | Qt.AlignHCenter)
        self.export_btn=QPushButton('保存预设')
        self.export_btn.setStyleSheet(btn_style)
        self.export_btn.clicked.connect(self.export_prefab)
        self.project_setting_layout.addWidget(self.import_btn)
        self.project_setting_layout.addWidget(self.per_project_label)
        self.project_setting_layout.addWidget(self.export_btn)
        # self.project_UI.addWidget(self.per_project_label)
        self.project_UI.addLayout(self.project_setting_layout)
        self.init_project(self.project_list)
        self.project_scroll.setWidget(self.project_widget)
        self.left_layout.addWidget(self.left_label)
        self.left_layout.addWidget(self.spline)
        self.left_layout.addWidget(self.patch_btn)
        self.left_layout.addLayout(self.all_project_setting_layout)
        self.left_layout.addWidget(self.spline1)
        # self.left_layout.addLayout(self.project_UI)
        self.left_layout.addWidget(self.project_scroll)
        # self.left_layout.addWidget(self.scrollbar)
        # self.left_layout.addWidget(self.project_widget)
        self.create_layout=QHBoxLayout()
        self.create_btn=QPushButton('生成每月表')
        self.create_btn.setStyleSheet(btn_style)
        self.create_btn.clicked.connect(self._create)
        self.update_btn=QPushButton('更新每月表')
        self.update_btn.setStyleSheet(btn_style)
        self.update_btn.clicked.connect(self._update)
        self.create_layout.addWidget(self.create_btn)
        self.create_layout.addWidget(self.update_btn)
        self.left_layout.addLayout(self.create_layout)

        self.left_frame.setLayout(self.left_layout)

        self.right_frame=QFrame()
        self.right_layout=QVBoxLayout()
        self.right_label=QLabel('每月人员工资项目列表')
        self.right_label.setAlignment(Qt.AlignHCenter)
        self.right_listwidget=ArtistWidget({},{})
        self.right_layout.addWidget(self.right_label)
        self.right_layout.addWidget(self.right_listwidget)
        self.right_frame.setLayout(self.right_layout)

        self.hSplitter.addWidget(self.left_frame)
        self.hSplitter.addWidget(self.right_frame)
        self.hSplitter.setSizes([450, 800])
        self.main_layout.addWidget(self.hSplitter)
        # self.main_layout.addWidget(self.right_frame)
        self.setLayout(self.main_layout)

    def init_project(self,project_list):

        if project_list:
            for i in project_list:
                per_project_layout=QVBoxLayout()
                per_project_layout.setSpacing(7)
                per_project_layout.setContentsMargins(15,15,5,15)
                project_label=QLabel(i)
                project_label.setFont(self.m_font)
                project_label.setAlignment(Qt.AlignHCenter)
                h_layout=QHBoxLayout()
                h_layout.setAlignment(Qt.AlignLeft)
                project_cost_label=QLabel('总额:')
                project_cost_label.setFont(self.l_font)
                project_edit=QLineEdit()
                project_edit.textChanged.connect(self._per_cost_changed)
                # project_edit.setMinimumWidth(80)
                project_edit.setValidator(self.rv)
                month_label=QLabel('  月数:')
                month_label.setFont(self.l_font)
                month_eidt=QLineEdit()
                month_eidt.textChanged.connect(self._month_change)
                per_month_label=QLabel('   月平均:')
                per_month_label.setFont(self.l_font)
                per_month_value_label=QLabel()

                h_layout.addWidget(project_cost_label)
                h_layout.addWidget(project_edit)
                h_layout.addWidget(month_label)
                h_layout.addWidget(month_eidt)
                h_layout.addWidget(per_month_label)
                h_layout.addWidget(per_month_value_label)
                per_project_layout.addWidget(project_label)
                # per_project_layout.addWidget(project_edit)
                per_project_layout.addLayout(h_layout)
                self.project_edit_list.append(project_edit)
                self.month_edit_list.append(month_eidt)
                self.per_month_value_label_list.append(per_month_value_label)

                self.project_UI.addLayout(per_project_layout)

    def _all_cost_changed(self,text):
        print(text)
        if text:
            self.all_cost=float(text)
            self._per_cost_changed('OK')

    def _per_cost_changed(self,change):
        """
        每项目填写值变换
        :param text:
        :return:
        """
        cost=0 #每个项目的额度添加
        for i in self.project_edit_list:
            text=i.text()
            value=0
            if text:
                value=float(text)
            cost+=value
        print(text)
        ye_value=self.all_cost-cost
        ye='    余额： {}'.format(ye_value)
        if ye_value<0:
            self.all_project_left_cost_label.setStyleSheet('color:#FF4500')
        else:
            self.all_project_left_cost_label.setStyleSheet('color:#000000')
        self.all_project_left_cost_label.setText(ye)

    def _month_change(self,change):
        """
        当月份改变时
        :param change:
        :return:
        """
        for i in range(len(self.project_edit_list)):
            project_edit=self.project_edit_list[i]
            month_eidt=self.month_edit_list[i]
            per_month_label=self.per_month_value_label_list[i]
            project_cost=project_edit.text()
            month=month_eidt.text()
            print(project_cost,month)

            project_cost_value=float(project_cost) if project_cost else 0
            month_value=float(month) if month else 0
            if month_value:
                per_month_value=round(project_cost_value/month_value,2)
                per_month_label.setText(str(per_month_value))
            else:
                per_month_label.setText('0')

    def checkMonth(self):
        is_ok=True
        for i in self.month_edit_list:
            if not i.text():
                is_ok=False
                break
        return is_ok

    def _set_salary(self):
        """
        匹配人员工资
        :return:
        """
        salary_data={'张三':15000,'李四':23000,'王五':30000,'赵六':9000,'小明':5000,'李淳罡':45000,'黄蛮儿':23000,'洛阳':32000,'马云':10000}

        self.right_listwidget.setSalary(salary_data)



    def _create(self):
        """
        生成每月人员表
        :return:
        """
        project_data=[]
        if self.checkMonth():
            for p in self.project_list:
                per_project_cost=self.per_month_value_label_list[self.project_list.index(p)].text()
                project_data.append((p,per_project_cost))
            self.right_listwidget.set_data(project_data,self.artist_data)
        else:
            QMessageBox.information(self,'提示','月份缺失')


    def _update(self):
        """
        更新每月人员表，主要就是平均每月值变换了，更新表头
        :return:
        """
        project_data=[]
        if self.checkMonth():
            for p in self.project_list:
                per_project_cost=self.per_month_value_label_list[self.project_list.index(p)].text()
                project_data.append((p,per_project_cost))
            self.right_listwidget.update_H(project_data)
        else:
            QMessageBox.information(self,'提示','月份缺失')


    def import_prefab(self):
        """
        导入预设
        :return:
        """
        openfile_name = QFileDialog.getOpenFileName(self, '选择预设', '', 'prefab files(*.pref , *.pre)')[0]
        print(openfile_name)
        s_data={}
        with open(openfile_name,'r',encoding='utf8') as r:
            s_data=r.read()
        data=eval(s_data)
        all_cost=data['all_cost']
        print('import_prefab 001')
        self.all_project_cost_edit.setText(all_cost)
        self.all_cost=float(all_cost)
        print('import_prefab 002')
        for i in self.project_list:
            project_info=data[i] if i in data.keys() else []
            print('import_prefab 003')
            if project_info:
                print('project_info:',project_info)
                index=self.project_list.index(i)
                print('import_prefab 004')
                per_project_cost=project_info[1]
                month_count=project_info[2]
                self.project_edit_list[index].setText(per_project_cost)
                print('import_prefab 005')
                self.month_edit_list[index].setText(month_count)

        print('import_prefab 006')
    def export_prefab(self):
        """
        导出配置
        :return:
        """
        openfile_name = QFileDialog.getSaveFileName(self, '保存预设', '', 'prefab files(*.pref , *.pre)')[0]
        print(openfile_name)
        save_data={}
        all_cost=str(self.all_cost)
        save_data['all_cost']=all_cost
        for i in self.project_list:
            index=self.project_list.index(i)
            per_project_cost=self.project_edit_list[index].text() if self.project_edit_list[index].text() else '0'   # 分项目总额edit列表
            month_count=self.month_edit_list[index].text() if self.month_edit_list[index].text() else '0'
            save_data[i]=[index,per_project_cost,month_count]
        try:
            with open(openfile_name,'w',encoding='utf8') as w:
                w.write(str(save_data))
        except Exception as export_prefab_ERR:
            print(str(export_prefab_ERR))
        print(save_data)

if __name__ == '__main__':
    app=QApplication(sys.argv)
    project_list=['项目A','项目B','项目C','项目D','项目E','项目F']#,'项目G','项目H','项目D','项目E','项目F','项目G','项目H'
    artist_data=[('张三',234.5,1),('李四',323.5,1),('王五',250.5,0),('赵六',222,1),('小明',213,0),('李淳罡',380,1),('黄蛮儿',325,0),('洛阳',321,0),('马云',222.2,0)]

    r=ResignedWindow(project_list,artist_data)
    r.show()


    # project_data=[('项目A',25),('项目B',50),('项目C',70),('项目D',35),('项目E',23.5),('项目F',33.2)]
    # artist_data=[('张三',234.5,1),('李四',323.5,1),('王五',250.5,0),('赵六',222,1),('小明',213,0),('李淳罡',380,1),('黄蛮儿',325,0),('洛阳',321,0),('马云',222.2,0)]
    # salary_data={'张三':15000,'李四':23000,'王五':30000,'赵六':9000,'小明':5000,'李淳罡':45000,'黄蛮儿':23000,'洛阳':32000,'马云':10000}
    # a=ArtistWidget(project_data,artist_data)
    # a.setSalary(salary_data)
    # a.show()
    sys.exit(app.exec_())
